//
//  ChapterDAL.m
//  readNovels
//
//  Created by 吳瀾洲 on 2020/4/27.
//  Copyright © 2020 wulanzhou. All rights reserved.
//

#import "ChapterDAL.h"
#import "BookDBManager.h"
#import "Chapter.h"
#import "ChapterSQL.h"

@implementation ChapterDAL

- (NSArray <Chapter *> *)chapterWithBookId:(NSInteger)book_id{

    return [[BookDBManager shareInstance] queryDBWithModels:[Chapter class] sql:query_book_id_chapter,[NSNumber numberWithInteger:book_id], nil];
}

#pragma mark - DBInterface Methods
- (BOOL)Insert:(Chapter *)chapter{
    
    NSDateFormatter*dateFormat =[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSInteger finishedValue = chapter.finished ? 1 : 0;
    BOOL success=[[BookDBManager shareInstance] updataDBWithSql:insert_chapter_sql,[NSNumber numberWithInteger:chapter.catalog_id],chapter.title,chapter.content,[NSNumber numberWithInteger:finishedValue],[NSNumber numberWithInteger:chapter.sort],chapter.memo,[dateFormat stringFromDate:chapter.ctime],[dateFormat stringFromDate:chapter.mtime], nil];
    
    if (success) {
        NSLog(@"新增章节=(%@)成功!",chapter.title);
    }else{
        NSLog(@"新增章节=(%@)失败!",chapter.title);
    }
    return success;
}

- (BOOL)Update:(Chapter *)chapter{
    
    NSDateFormatter*dateFormat =[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    BOOL success = NO;
    NSInteger finishedValue = chapter.finished ? 1 : 0;
    if (chapter.content&&[chapter.content length] > 0) {
        success = [[BookDBManager shareInstance] updataDBWithSql:update_chapter_content,chapter.content,[NSNumber numberWithInteger:finishedValue],[dateFormat stringFromDate:chapter.mtime],[NSNumber numberWithInteger:chapter.catalog_id], nil];
    }else{
        success = [[BookDBManager shareInstance] updataDBWithSql:update_chapter_status,[NSNumber numberWithInteger:finishedValue],[dateFormat stringFromDate:chapter.mtime],[NSNumber numberWithInteger:chapter.catalog_id], nil];
    }
    
    if (success) {
        NSLog(@"修改章节=(%@)成功!",chapter.title);
    }else{
        NSLog(@"修改章节=(%@)失败!",chapter.title);
    }
    
    return success;

}

- (BOOL)Delete:(id)kId{
   NSInteger primaryKey = [kId integerValue];
    
   return [[BookDBManager shareInstance] updataDBWithSql:delete_chapter_catalog_id,[NSNumber numberWithInteger:primaryKey], nil];
    //delete_chapter_catalog_id
}

- (Chapter *)Entity:(id)catalog_id{

    NSInteger primaryKey = [catalog_id integerValue];
    NSArray *source = [[BookDBManager shareInstance] queryDBWithModels:[Chapter class] sql:query_catalog_id_chapter,[NSNumber numberWithInteger:primaryKey], nil];
    
    if (source && [source count] >0) {
        
        return source[0];
    }
    return nil;
    
}

@end
